package com.project.internship.controller;

import com.project.internship.entity.User;
import com.project.internship.entity.chat.ChatMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.util.Date;

/**
 * websocket 聊天
 */
@Controller
public class WsController {
    //websocket内置的消息发送模板
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication auth, ChatMsg chatMsg){
        //获取当前用户对象
        User principal = (User) auth.getPrincipal();
        //设置ChatMsg内容
        chatMsg.setFrom(principal.getUsername());
        chatMsg.setFromNickName(principal.getName());
        chatMsg.setDate(new Date());
        //推送消息需要推送到指定的用户  推送用户   接口   消息对象
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }

}
